package com.taojiazheng.serviceImpl.history;

import com.taojiazheng.dao.user.UserDao;
import com.taojiazheng.entity.History;
import com.taojiazheng.entity.User;
import com.taojiazheng.mapper.HistoryMapper;
import com.taojiazheng.service.history.HistoryService;
import com.taojiazheng.vo.history.HistoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 赵成林
 * @date 2018/1/4 18:23
 */
@Service
public class HistoryServiceImpl implements HistoryService {
    @Autowired
    private HistoryMapper historyMapper;
    @Autowired
    private UserDao userDao;

    @Override
    public void createHistory(History history, String token) {
        User user = userDao.getUserByToken(token);
        history.setUserId(user.getId());
        history.setDate(new Date());
        history.setUpdateDate(new Date());
        Boolean value = this.isHaveHistory(history.getJobId(), user.getId());
        if (value) {
            historyMapper.insert(history);
        } else {
            Map map = new HashMap();
            map.put("updateDate", new Date());
            map.put("userId", user.getId());
            map.put("jobaId", history.getJobId());
            historyMapper.updateTime(map);
        }

    }

    /**
     * 获取列表
     * @param token
     * @return
     */
    @Override
    public List<HistoryVo> getHistory(String token) {
       // return null;
        User user = userDao.getUserByToken(token);
        return historyMapper.getHistorys(user.getId());
    }

    /**
     * 判断是否已经有记录
     * 如果有记录进行更新的操作
     * 而不是插入的操作
     *
     * @param jobId
     * @param userId
     * @return
     */
    protected boolean isHaveHistory(Integer jobId, Integer userId) {
        Map map = new HashMap();
        map.put("userId", userId);
        map.put("jobId", jobId);
        History history = historyMapper.getHistoryByJobAndUser(map);
        if (history != null) {
            return false;
        }
        return true;
    }

    @Override
    public void deleteHistory(String token) {
        User user = userDao.getUserByToken(token);
        Integer userId = user.getId();
        historyMapper.deleteHistory(userId);
    }
}
